<?php

namespace App\Http\Controllers\Wechat;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use EasyWechat\Foundation\Application;
use App\nav;

class MenuController extends Controller
{
    /**
     * 生成自定义菜单栏
     */
    public function makeMenu()
    {
        $nav=nav::where('pid','0')->get();//获取父级级菜单
        $buttons=array();
        foreach ($nav as $value) {
            $id = $value->id;
            $child = nav::where('pid', $id)->get();//根据pid获取子级
            foreach ($nav as $value) {
                $id = $value->id;
                $child = nav::where('pid', $id)->get();//根据pid获取子级
                $oneNav = array();
                if (count($child) > 0) {//有子级的父级

                    $oneNav['name'] = $value->nav_name;
                    //拼接菜单栏字符串
                    foreach ($child as $v) {
                        $nav_type = $v->nav_type;//子级菜单类型
                        $nav_child = array();
                        if ($nav_type == 'click') {
                            $nav_child['type'] = 'click';
                            $nav_child['name'] = $v->nav_name;
                            $nav_child['key'] = $v -> value;
                            $oneNav['sub_button'][] = $nav_child;
                        } elseif ($nav_type == 'view') {
                            $nav_child['type'] = 'view';
                            $nav_child['name'] = $v->nav_name;
                            $nav_child['url'] = $v -> value;
                            $oneNav['sub_button'][]= $nav_child;
                        }
                    }

                } elseif (count($child) == 0) {//无子级的父级
                    if ($nav->nav_type == 'click') {
                        $nav_child['type'] = 'click';
                        $nav_child['name'] = $nav->nav_name;
                        $nav_child['key'] = $nav -> value;
                        $oneNav['sub_button'] = $nav_child;
                    } elseif ($nav->nav_type == 'view') {
                        $nav_child['type'] = 'view';
                        $nav_child['name'] = $nav->nav_name;
                        $nav_child['url'] = $nav ->value;
                        $oneNav['sub_button'] = $nav_child;
                    }
                }
            }
            $buttons [] = $oneNav;
        }
        $wechat = app('wechat');
        $result = $wechat->menu->add($buttons);
        dump($result);
    }
}
